package com.example.tms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.example.tms.entity.Employee;
import com.example.tms.mapper.EmployeeMapper;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public UserDetails loadUserByUsername(String identifier) throws UsernameNotFoundException {
        Employee employee;
        
        // 判断是ID还是手机号
        if (identifier.matches("\\d{11}")) { // 手机号格式
            employee = employeeMapper.selectOneByPhone(identifier);
        } else { // 当作ID处理
            try {
                employee = employeeMapper.selectById(Integer.parseInt(identifier));
            } catch (NumberFormatException e) {
                throw new UsernameNotFoundException("无效的用户标识: " + identifier);
            }
        }
        
        if (employee == null) {
            throw new UsernameNotFoundException("用户不存在: " + identifier);
        }
        
        if (employee.getId() == null) {
            throw new UsernameNotFoundException("用户数据异常: ID为空");
        }
        
        return employee;
    }
}
